package com.canin.login.action;

import java.util.Map;

import org.apache.struts2.interceptor.SessionAware;

import com.canin.Constant;
import com.canin.dao.AdminDAO;
import com.canin.dao.DAOFactory;
import com.canin.dao.MemberDAO;
import com.canin.login.form.LoginForm;
import com.canin.model.Admin;
import com.canin.model.Member;
import com.opensymphony.xwork2.ActionSupport;

public class LoginAction extends ActionSupport implements SessionAware
{
	private static final long serialVersionUID = -1448585674545692665L;
	private LoginForm loginForm;
	private Map<String, Object> userSession;

	public String execute() throws Exception
	{
		System.out.println( "admin login? : " + loginForm.isAdminLogin() );
		
		userSession.clear();
		String result = INPUT;

		DAOFactory daoFactory = new DAOFactory();

		try
		{
			daoFactory.beginConnection();
			
			if ( loginForm.isAdminLogin() )
			{
				AdminDAO adminDAO = daoFactory.createAdminDAO();

				Admin admin = adminDAO.getAdminByUserPass(loginForm.getUsername(),
						loginForm.getPassword());
				
				if (admin != null)
				{
					userSession.put(Constant.ADMIN, admin);
					result = "adminSuccess";
				}
			}
			else
			{
				MemberDAO memberDAO = daoFactory.createMemberDAO();

				Member member = memberDAO.getMemberByUserPass(loginForm.getUsername(),
						loginForm.getPassword());
				
				if (member != null)
				{
					userSession.put(Constant.MEMBER, member);
					System.out.println("First Name : " + member.getFirst_Name());
					result = "memberSuccess";
				}
				
			}

			daoFactory.endConnection();
			
			if ( !result.contains( "Success" ) )
			{
				addActionError(getText("msg.loginFail"));
			}
			
		}
		catch (Exception e)
		{
			e.printStackTrace();
			addActionError(getText("error.dao"));
			result = ERROR;
		}
		finally
		{
			daoFactory.endConnection();
		}

		return result;
	}
	
	public String logout()
	{
		userSession.clear();
		addActionMessage(getText("msg.logout"));
		return INPUT;
	}

	public void validate()
	{
		// addActionError("msg.loginFail");
//		System.out.println("You are valid user!");
//		addActionMessage("You are valid user!");
	}

	public LoginForm getLoginForm()
	{
		return loginForm;
	}

	public void setLoginForm(LoginForm loginForm)
	{
		this.loginForm = loginForm;
	}

	@Override
	public void setSession(Map<String, Object> session)
	{
		this.userSession = session;
	}

}
